﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using twlib;

namespace TeamWork_Server
{
    public class SubscriptionService
    {
        Socket s;

        public SubscriptionService()
        {
            s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        private void xRun()
        {
            while (true)
            {
                Socket sc = s.Accept();
                byte[] bts = new byte[30*1024];
                sc.ReceiveBufferSize = 30 * 1024;
                sc.SendBufferSize = 30 * 1024;
                sc.Receive(bts);
                Q1.RRR.BasicQ1BinaryFormation bfmt = new Q1.RRR.BasicQ1BinaryFormation();
                try
                {
                    byte[] bts_d = bfmt.DePatch(bts);
                    UserCommand cmd = (UserCommand)Serialization.BinaryDeserialize(bts_d);
                    Subscriptions.SubscriptionHandler handler = new Subscriptions.SubscriptionHandler(cmd);
                    object[] obb = handler.Handle();
                    ServerResponse response = new ServerResponse((bool)obb[0], long.Parse(CommandsFactory.Variables["admin_master_key"].ToString()), (string)obb[1], null);
                    byte[] bts_res_d = Serialization.BinarySerialize(response);
                    byte[] bb = bfmt.Patch(bts_res_d);
                    sc.Send(bb);
               }
                catch (Exception ex)
                {
                    //string response_str = "";
                    if (ex is Q1.RRR.BasicQ1BinaryFormationDePatchException)
                    {
                        Log.Error("Error during the packet decryption. Packet was probably invalid.");
                    }
                    else if(ex is Q1.RRR.BasicQ1BinaryFormationPatchException)
                    {
                        Log.Error("Error during the ecryption of the response packet.");
                    }
                    else if (ex is System.Runtime.Serialization.SerializationException)
                    {
                        Log.Error("Error during the packet deserialization. Packet was probably invalid.");
                    }
                    else
                    {
                        Log.Error("Unexpected error during the RCON CMD Handler operation.");
                    }
                    ServerResponse response = new ServerResponse(false, 0x00, "", null);
                    byte[] bts_res_d = Serialization.BinarySerialize(response);
                    byte[] bb = bfmt.Patch(bts_res_d);
                    sc.Send(bb);
                }
            }
        }

        public void Start()
        {
            s.Bind((EndPoint)(new IPEndPoint(IPAddress.Any, 5522)));
            s.Listen(100);
            new Thread(xRun).Start();
            Log.Debug("Subscription Service Is Now Operating");
        }
    }
}
